package com.zhugang.week06;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: levelOrderGroup
 * @author: chanzhugang
 * @create: 2022/07/15 16:16
 */
public class LevelOrderGroup2 {

    /**
     * 102 二叉树的层序遍历
     *
     * @param root
     * @return
     */
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        // 前序遍历：记录每层层号
        dfs(root, 0);
        return result;
    }

    private void dfs(TreeNode root, int level) {
        if (root == null) {
            return;
        }
        if (level > result.size() - 1) {
            result.add(new ArrayList<>());
        }
        result.get(level).add(root.val);
        dfs(root.left, level + 1);
        dfs(root.right, level + 1);

    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}